import { login } from '../../api/sys'
import { setItem, getItem } from '../../utils/storage'
import md5 from 'js-md5'
import { TOKEN } from '../../constant/index'
import router from '@/router'

export default {
    namespaced: true,
    state: () => ({
        token: getItem(TOKEN) || ''
    }),
    mutations: {
        setToken(state, token){
            state.token = token
            setItem(TOKEN, token)
        }
    },
    actions: {
        login({ commit }, loginForm) {
            const { username, password } = loginForm
            return new Promise((resolve, reject) => {
                login({ username: username, password: md5(password) }).then(res => {
                    // console.log(res);
                    commit('setToken', res.token)
                    router.push('/layout')
                    resolve(res)
                }).catch(err => {
                    reject(err)
                })
            })
        }
    }
}